package study.itheima.myrequest;

import org.apache.commons.beanutils.BeanUtils;
import study.itheima.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Map;

@WebServlet("/RequestPractice1")
public class RequestPractice1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String contextPath = req.getContextPath();//获取虚拟目录
        System.out.println("contextPath = " + contextPath);
        String servletPath = req.getServletPath();//获取映射路径
        System.out.println("servletPath = " + servletPath);
        String uri = req.getRequestURI();
        System.out.println("uri = " + uri);
        String remoteAddr = req.getRemoteAddr();//获取ip
        System.out.println("remoteAddr = " + remoteAddr);
        //获取指定的头信息
        String referer = req.getHeader("Referer");
        System.out.println("referer = " + referer);
        String userAgent = req.getHeader("User-Agent");
        System.out.println("userAgent = " + userAgent);
        System.out.println("================");
        //工具类封装为javabean对象
        req.setCharacterEncoding("UTF-8");
        Student stu = new Student();
        Map<String, String[]> map = req.getParameterMap();
        try {
            BeanUtils.populate(stu,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(stu);
        System.out.println("==========");
        //二个获取请求参数的方法
        String username = req.getParameter("username");
        System.out.println("username = " + username);
        String[] hobbies = req.getParameterValues("hobby");
        System.out.println("hobbies = " + Arrays.toString(hobbies));
        System.out.println("==========");
        //转发
        req.setAttribute("encoding","gbk");
        req.getRequestDispatcher("RequestPractice2").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
